﻿namespace com.stifel.ServerBuildMgmt.BuildMgmtBackupInfo
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Caching;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    using com.stifel.Extensions.StringExtensions;
    using com.stifel.ServerBuildMgmtDao;

    using Microsoft.SharePoint;

    public partial class BuildMgmtBackupInfoUserControl
    {
        #region Fields

        string _sitecollectionurl;
        string _UrlReferrer;

        #endregion Fields

        #region Properties

        string sitecollectionurl
        {
            get
            {
                if ( string.IsNullOrEmpty( _sitecollectionurl ) )
                {
                    SPSite spSite = SPContext.Current.Site;
                    _sitecollectionurl = spSite.Url;
                }
                return _sitecollectionurl;
            }
        }

        int summaryRow
        {
            get;
            set;
        }

        string UrlReferrer
        {
            get
            {
                if ( string.IsNullOrEmpty( _UrlReferrer ) )
                    _UrlReferrer = ( string ) Page.Cache.Get( CacheKey.UrlReferrer );
                if ( string.IsNullOrEmpty( _UrlReferrer ) )
                    setUrlReferrer( );
                return _UrlReferrer;
            }
            set
            {
                _UrlReferrer = value;
                addToCache( CacheKey.UrlReferrer, value );
            }
        }

        #endregion Properties

        #region Methods

        public void AddRequestToList( StifelVirtualServerRequest request )
        {
            StifelServerBuildDao dao = new StifelServerBuildDao( );
            StifelVirtualServerRequest AddedRequest = dao.Upsert( request );
            string absUrl = getUrl( );
            Page.Response.Redirect( absUrl.Append( "?ItemGuid=" + AddedRequest.UniqueId.ToString( ) ) );
        }

        public string AddRequestToListButNoRedirect( StifelVirtualServerRequest request )
        {
            StifelServerBuildDao dao = new StifelServerBuildDao( );
            StifelVirtualServerRequest AddedRequest = dao.Upsert( request );
            string absUrl = getUrl( );
            return ( absUrl.Append( "?ItemGuid=" + AddedRequest.UniqueId.ToString( ) ) );
        }

        public void cleanErrorMsg( )
        {
            uiLblRetentionTimeErrorMsg.Text = string.Empty;
            uiLblAgentsErrorMsg.Text = string.Empty;
            uiLblPolicyErrorMsg.Text = string.Empty;
        }

        public StifelVirtualServerRequest getRequestInfo( )
        {
            Guid ItemGuid = HttpContext.Current.Request.QueryString[ "ItemGuid" ].ToGuid( );
            StifelServerBuildDao dao = new StifelServerBuildDao( );
            StifelVirtualServerRequest request = dao.getRequestFromListUsingGUID( ItemGuid );
            if ( request != null )
            {
                VirtualServerCollectionClass v = new VirtualServerCollectionClass( );
                foreach ( RepeaterItem r in myRepeater.Items )
                {
                    HiddenField hiddenField = ( HiddenField ) r.FindControl( "valuePart" );
                    v.virtualServerCollection.Add( hiddenField.Value.FromBase64String( ).DeserializeFromXml<ServerValues>( ) );
                }
                request.SerializedVirtualServerRequest = request.SerializeVirtualServerCollectionClass( v );
            }
            return ( request );
        }

        public void SaveServers( )
        {
            StifelVirtualServerRequest request = getRequestInfo( );
            request.SetForBackUpSave( );
            AddRequestToList( request );
        }

        public void setErrorMsg( )
        {
            if ( uiDdlPolicy.SelectedItem.Text.Trim( ) == string.Empty )
            {
                uiLblPolicyErrorMsg.Text = "Please Select Policy Before Checking Completed.";
            }
            else
            {
                uiLblPolicyErrorMsg.Text = string.Empty;
            }
            if ( uiDdlAgents.SelectedItem.Text.Trim( ) == string.Empty )
            {
                uiLblAgentsErrorMsg.Text = "Please Select Agents Before Checking Completed.";
            }
            else
            {
                uiLblAgentsErrorMsg.Text = string.Empty;
            }
            if ( uiDdlRetentionTime.SelectedItem.Text.Trim( ) == string.Empty )
            {
                uiLblRetentionTimeErrorMsg.Text = "Please Select Rentention Time Before Checking Completed.";
            }
            else
            {
                uiLblRetentionTimeErrorMsg.Text = string.Empty;
            }
        }

        public void SubmitServers( )
        {
            StifelVirtualServerRequest request = getRequestInfo( );
            request.SetForBackUpSubmit( );
            string redirector = AddRequestToListButNoRedirect( request );
            if ( ( redirector != null ) && ( redirector != string.Empty ) )
            {
                if ( redirector.Equals( UrlReferrer, StringComparison.InvariantCultureIgnoreCase ) )
                {
                    Page.Response.Redirect( redirector );
                }
                else
                {
                    Page.Response.Redirect( UrlReferrer );
                }
            }
        }

        //TODO
        public void uiDdlAgents_Load( string selectedAgent )
        {
            StifelBackupAgentDao dao = new StifelBackupAgentDao( );
            List<StifelAgent> listItems = dao.GetAllActiveItems( );
            uiDdlAgents.Items.Clear( );
            if ( listItems.Count == 0 )
            {
                uiDdlAgents.Items.Add( new ListItem( string.Empty, string.Empty ) );
            }
            else if ( listItems.Count == 1 )
            {
                foreach ( StifelAgent sa in listItems )
                {
                    ListItem li = new ListItem( sa.Title.ToString( ), sa.Title.ToString( ) );
                    if ( ( selectedAgent != null ) && ( selectedAgent != string.Empty ) )
                    {
                        li.Selected = selectedAgent.Equals( sa.Title.ToString( ), StringComparison.InvariantCultureIgnoreCase );
                    }
                    uiDdlAgents.Items.Add( li );
                }
            }
            else
            {
                uiDdlAgents.Items.Add( new ListItem( string.Empty, string.Empty ) );
                foreach ( StifelAgent sa in listItems )
                {
                    ListItem li = new ListItem( sa.Title.ToString( ), sa.Title.ToString( ) );
                    if ( ( selectedAgent != null ) && ( selectedAgent != string.Empty ) )
                    {
                        li.Selected = selectedAgent.Equals( sa.Title.ToString( ), StringComparison.InvariantCultureIgnoreCase );
                    }
                    uiDdlAgents.Items.Add( li );
                }
            }
        }

        //TODO
        public void uiDdlPolicy_Load( string selectedPolicy )
        {
            StifelBackupPolicyDao dao = new StifelBackupPolicyDao( );
            List<StifelPolicy> listItems = dao.GetAllActiveItems( );
            uiDdlPolicy.Items.Clear( );
            if ( listItems.Count == 0 )
            {
                uiDdlPolicy.Items.Add( new ListItem( string.Empty, string.Empty ) );
            }
            else if ( listItems.Count == 1 )
            {
                foreach ( StifelPolicy sp in listItems )
                {
                    ListItem li = new ListItem( sp.Title.ToString( ), sp.Title.ToString( ) );
                    if ( ( selectedPolicy != null ) && ( selectedPolicy != string.Empty ) )
                    {
                        li.Selected = selectedPolicy.Equals( sp.Title.ToString( ), StringComparison.InvariantCultureIgnoreCase );
                    }
                    uiDdlPolicy.Items.Add( li );
                }
            }
            else
            {
                uiDdlPolicy.Items.Add( new ListItem( string.Empty, string.Empty ) );
                foreach ( StifelPolicy sp in listItems )
                {
                    ListItem li = new ListItem( sp.Title.ToString( ), sp.Title.ToString( ) );
                    if ( ( selectedPolicy != null ) && ( selectedPolicy != string.Empty ) )
                    {
                        li.Selected = selectedPolicy.Equals( sp.Title.ToString( ), StringComparison.InvariantCultureIgnoreCase );
                    }
                    uiDdlPolicy.Items.Add( li );
                }
            }
        }

        //TODO
        public void uiDdlRetentionTime_Load( string selectedRetentionTime )
        {
            StifelBackupRetentionDao dao = new StifelBackupRetentionDao( );
            List<StifelBackupRetention> listItems = dao.GetAllActiveItems( );
            uiDdlRetentionTime.Items.Clear( );
            if ( listItems.Count == 0 )
            {
                uiDdlRetentionTime.Items.Add( new ListItem( string.Empty, string.Empty ) );
            }
            else if ( listItems.Count == 1 )
            {
                foreach ( StifelBackupRetention sbr in listItems )
                {
                    ListItem li = new ListItem( sbr.Title.ToString( ), sbr.Title.ToString( ) );
                    if ( ( selectedRetentionTime != null ) && ( selectedRetentionTime != string.Empty ) )
                    {
                        li.Selected = selectedRetentionTime.Equals( sbr.Title.ToString( ), StringComparison.InvariantCultureIgnoreCase );
                    }
                    uiDdlRetentionTime.Items.Add( li );
                }
            }
            else
            {
                uiDdlRetentionTime.Items.Add( new ListItem( string.Empty, string.Empty ) );
                foreach ( StifelBackupRetention sbr in listItems )
                {
                    ListItem li = new ListItem( sbr.Title.ToString( ), sbr.Title.ToString( ) );
                    if ( ( selectedRetentionTime != null ) && ( selectedRetentionTime != string.Empty ) )
                    {
                        li.Selected = selectedRetentionTime.Equals( sbr.Title.ToString( ), StringComparison.InvariantCultureIgnoreCase );
                    }
                    uiDdlRetentionTime.Items.Add( li );
                }
            }
        }

        //void summarize( string arg )
        //{
        //    summarize_backupInfo( arg );
        //    //summarize_buttonTwo( arg );
        //}
        public bool ValidateBackup( )
        {
            bool ok = true;
            if ( uiCbBackupCompletedFlag.Checked )
            {
                if ( ( uiDdlPolicy.SelectedItem.Text.Trim( ) == string.Empty ) || ( uiDdlAgents.SelectedItem.Text.Trim( ) == string.Empty ) || ( uiDdlRetentionTime.SelectedItem.Text.Trim( ) == string.Empty ) )
                {
                    ok = false;
                }
            }
            return ( ok );
        }

        public bool Validation( )
        {
            bool ok = ValidateBackup( );
            if ( !ok )
            {
                uiCbBackupCompletedFlag.Checked = false;
                setErrorMsg( );
            }
            else
            {
                cleanErrorMsg( );
            }
            return ( ok );
        }

        Panel addPanel( Panel p )
        {
            Panel ret = new Panel( );
            ret = p;
            return ( ret );
        }

        void addToCache( string key, object value )
        {
            if ( value == null )
                Cache.Remove( key );
            else
                // cache for 10 hours
                Cache.Insert( key, value, null,
                    Cache.NoAbsoluteExpiration,
                    new TimeSpan( 10, 0, 0 ),
                    CacheItemPriority.Normal,
                    new CacheItemRemovedCallback(
                        delegate( string k, object v, CacheItemRemovedReason reason )
                        {
                        } ) );
        }

        TableRow buildSummary( Literal literal, TextBox textbox )
        {
            TableRow r = new TableRow( );
            TableCell c = new TableCell( );
            c.Style.Add( HtmlTextWriterStyle.TextAlign, TextAlign.Left );
            c.CssClass = CssClass.Label;
            c.Controls.Add( new Literal
            {
                Text = literal.Text.TrimEnd( ) + " " + textbox.Text.Trim( )
            } );
            r.Cells.Add( c );
            r.CssClass = tableclass( );
            return r;
        }

        TableRow buildSummary( string value )
        {
            TableRow r = new TableRow( );
            TableCell c = new TableCell( );
            c.Style.Add( HtmlTextWriterStyle.TextAlign, TextAlign.Left );
            c.CssClass = CssClass.Data;
            c.Controls.Add( new Literal
            {
                Text = value.Trim( )
            } );
            r.Cells.Add( c );

            r.CssClass = tableclass( );
            return r;
        }

        string checkStatus( string strGUID )
        {
            StifelServerBuildDao dao = new StifelServerBuildDao( );
            StifelVirtualServerRequest r = dao.Get( strGUID.ToGuid( ) );
            r.IsRequestorStarted( );
            if ( r == null )
            {
                return string.Empty;
            }
            else
            {
                return r.RequestorStatus.ToString( );
            }
        }

        void flushcache( )
        {
            foreach ( string k in CacheKey.Values )
                Cache.Remove( k );
        }

        int getSplitCount( string url )
        {
            string[ ] split = url.Split( '?' );
            return ( split.Length );
        }

        string getUrl( )
        {
            string absUrl = HttpContext.Current.Request.Url.AbsoluteUri;
            string[ ] split = absUrl.Split( '?' );
            return ( split[ 0 ].ToString( ) );
        }

        void isSomethingChanged( )
        {
            if ( isChanged.Value.Equals( "true", StringComparison.InvariantCultureIgnoreCase ) )
            {
                uiBtnSave.Enabled = true;
            }
            else
            {
                uiBtnSave.Enabled = false;
            }
        }

        void navigateToSelectedView( Button button )
        {
            string arg = button.CommandArgument;
            int index = -1;

            for ( int i = 0; i < uiView.Views.Count; i++ )
            {
                View view = uiView.Views[ i ];
                if ( view.ID.Equals( arg, StringComparison.OrdinalIgnoreCase ) )
                {
                    index = i;
                    break;
                }
            }
            uiView.ActiveViewIndex = index >= 0 ? index : uiView.Views.Count - 1;
            foreach ( Control c in uiNavigation.Controls )
            {
                Button b = c as Button;
                if ( b != null )
                {
                    b.Attributes.Remove( Attribute.Current );
                }
            }
            button.Attributes.Add( Attribute.Current, true.ToString( ) );
        }

        void PageLoadBackUP( )
        {
            uiBackup.Visible = false;
            uiBackupUpdatePanel.Visible = false;
            uiBackBadUrlRequest.Visible = true;
        }

        string panelsToHtmlString( Panel p )
        {
            //Converting the comman panel to HTML string.
            StringWriter s = new StringWriter( );
            p.RenderControl( new HtmlTextWriter( s ) );
            return ( s.ToString( ) );
        }

        void setDefaultButton( )
        {
            Button button = uiBackupUpdatePanel.FindControl( "uiBtnBackUp" ) as Button;
            navigateToSelectedView( button );
            //summarize( button.CommandArgument );
        }

        void setSubmitValidation( )
        {
            int counter = 0;
            foreach ( RepeaterItem item in myRepeater.Items )
            {
                HiddenField h = ( HiddenField ) item.FindControl( "valuePart" );
                if ( ( h.Value.FromBase64String( ).DeserializeFromXml<ServerValues>( ).Backup.CompletedFlag == false ) || ( h.Value.FromBase64String( ).DeserializeFromXml<ServerValues>( ).Backup.CompletedFlag == null ) )
                {
                    uiBtnSubmit.Enabled = false;
                    counter = counter + 1;
                }
            }
            if ( counter == 0 )
            {
                uiBtnSave.Enabled = true;
                uiBtnSubmit.Enabled = true;
            }
            else
            {
                uiBtnSave.Enabled = true;
                uiBtnSubmit.Enabled = false;
            }
        }

        void setUrlReferrer( )
        {
            if ( Request != null && Request.UrlReferrer != null )
                UrlReferrer = Request.UrlReferrer.ToString( );
            else if ( Request != null )
                UrlReferrer = Request.Url.ToString( );
        }

        //void summarize_backupInfo( string arg )
        //{
        //    if ( arg.Equals( backupInfo.ID, StringComparison.OrdinalIgnoreCase ) )
        //    {
        //        Panel p = new Panel
        //        {
        //            GroupingText = uiPnlBackup.GroupingText
        //        };
        //        Table t = new Table( );
        //        t.Width = new Unit( 100, UnitType.Percentage );
        //        if ( uiCbBackupCompletedFlag.Checked )
        //        {
        //            t.Rows.Add( buildSummary( uiCbBackupCompletedFlag.Text.Trim( ) + " : " + "YES" ) );
        //        }
        //        else
        //        {
        //            t.Rows.Add( buildSummary( uiCbBackupCompletedFlag.Text + " : " + "NO" ) );
        //        }
        //        if ( ( uiDdlPolicy.SelectedItem.Text.Trim( ) != string.Empty ) && ( uiDdlPolicy.SelectedItem.Text.Trim( ) != null ) )
        //        {
        //            t.Rows.Add( buildSummary( uiLitPolicy.Text.Trim( ) + " " + uiDdlPolicy.SelectedItem.Text.Trim( ) ) );
        //        }
        //        if ( ( uiDdlAgents.SelectedItem.Text.Trim( ) != string.Empty ) && ( uiDdlAgents.SelectedItem.Text.Trim( ) != null ) )
        //        {
        //            t.Rows.Add( buildSummary( uiLitAgent.Text.Trim( ) + " " + uiDdlAgents.SelectedItem.Text.Trim( ) ) );
        //        }
        //        if ( ( uiDdlRetentionTime.SelectedItem.Text.Trim( ) != null ) && ( uiDdlRetentionTime.SelectedItem.Text.Trim( ) != string.Empty ) )
        //        {
        //            t.Rows.Add( buildSummary( uiLitRetentionTime.Text.Trim( ) + " " + uiDdlRetentionTime.SelectedItem.Text.Trim( ) ) );
        //        }
        //        if ( t.Rows.Count != 0 )
        //        {
        //            p.Controls.Add( t );
        //            uiPhBackupInfo.Controls.Clear( );
        //            uiPhBackupInfo.Controls.Add( p );
        //            //uiAntiVirusTab1.Controls.Add( p );
        //        }
        //    }
        //}
        //void summarize_buttonTwo( string arg )
        //{
        //    if ( arg.Equals( buttonTwo.ID, StringComparison.OrdinalIgnoreCase ) )
        //        return;
        //    Panel p = new Panel
        //    {
        //        GroupingText = uiPnlButtonOne.GroupingText
        //    };
        //    Table t = new Table( );
        //    t.Width = new Unit( 100, UnitType.Percentage );
        //    // server name
        //    if ( uiValBackUpNotes.Text.Trim( ) != string.Empty )
        //    {
        //        t.Rows.Add( buildSummary( "Notes : " + uiValBackUpNotes.Text ) );
        //    }
        //    if ( t.Rows.Count != 0 )
        //    {
        //        p.Controls.Add( t );
        //        uiAntiVirusTab2.Controls.Add( p );
        //    }
        //}
        string tableclass( )
        {
            //lock ( summaryRow )
            {
                string s = ( ( summaryRow % 2 ) == 0 ) ? CssClass.SummaryRowOdd : CssClass.SummaryRowEven;
                summaryRow++;
                return s;
            }
        }

        #endregion Methods

        #region Nested Types

        class Attribute
        {
            #region Fields

            public const string Current = "current";

            #endregion Fields
        }

        class CssClass
        {
            #region Fields

            public const string Data = "data";
            public const string Label = "label";
            public const string SummaryRowEven = "d1";
            public const string SummaryRowOdd = "d0";

            #endregion Fields
        }

        class TextAlign
        {
            #region Fields

            public const string Left = "left";
            public const string Right = "right";
            public const string summaryAdjustLeftPart = "summaryAdjustLeftPart";
            public const string summaryAdjustRightPart = "summaryAdjustRightPart";

            #endregion Fields
        }

        #endregion Nested Types
    }
}